Design Pattern: Adapter
Table of Contents
1. Adapter Design Pattern
Adapter is usually applied when endpoint processors cannot agree on the format of data, e.g., producers generates .xml files while consumers processes .json files.
So we can create adapters, which converts the interface of one object so that other objects can understand it. The adapter also wraps the object to hide the complexity of conversion.
1.1. How to Implement?
1.1.1. Object Adapter
We should have a ClientInterface that describes a protocol for other classes to follow, to be able to collaborate with the client code, say, the protocol is invoke(data) where data must follow a certain format. Also suppose some Service class with method serve(data_json) that requires special format.
The Adapter class implements the ClientInterface interface. The client have a pointer of class ClientInterface but points to an Adapter instance. Upon calling Adapter.invoke(data), Adapter converts data into data_json and invokes Service.serve(data_json).
1.1.2. Class Adapter
Similar to Object Adapter, the only difference is that Adapter class is also subclass of Service besides implementing ClientInterface interface.